﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using GRWL.BZSC.UI.BaseDataSvc;
using System.Collections;
using GRWL.BZSC.UI.CustomCtrl;
using UserCtrl;

namespace GRWL.BZSC.UI
{
    public partial class ProductionFrm : BaseFrm
    {
        private ArrayList FieldsRef = new ArrayList();
        bool bEdit, bConfirm, bPrint;

        /// <summary>
        /// 临时变量日期控件
        /// </summary>
        DateTimePicker _DTP = new DateTimePicker();
        UDataGridView theView;

        #region 窗体部分
        public ProductionFrm()
        {
            InitializeComponent();

            this.BaseDataProxy = new BaseDataClient();
            this.BaseDataProxy.Open();

            this.codeRule = new CodeRuleFrm.CodeRule();

            EditStatus = Common.BillOperateType.None;
            BillPrefix = "SCD";
        }

        private void ProductionFrm_Load(object sender, EventArgs e)
        {
            DisabledControls();

            theView = gvDetail1;
            theView.Controls.Add(this._DTP);  //把时间控件加入DataGridView
            this._DTP.Visible = false;  //先不让它显示
            this._DTP.Format = DateTimePickerFormat.Custom;
            this._DTP.TextChanged += new EventHandler(dtp_TextChange); //为时间控件加入事件dtp_TextChange            

            theView.CellClick += new DataGridViewCellEventHandler(theView_CellClick);
            theView.ColumnWidthChanged += new DataGridViewColumnEventHandler(theView_ColumnWidthChanged);
            theView.Scroll += new ScrollEventHandler(theView_Scroll);

            gvDetail1.CellDoubleClick += new DataGridViewCellEventHandler(gvDetail1_CellDoubleClick);
            gvDetail2.CellDoubleClick += new DataGridViewCellEventHandler(gvDetail2_CellDoubleClick);
            gvDetail3.CellDoubleClick += new DataGridViewCellEventHandler(gvDetail3_CellDoubleClick);
            gvDetail1.CellEndEdit += new DataGridViewCellEventHandler(gvDetail1_CellEndEdit);
            gvDetail1.RowsAdded += new DataGridViewRowsAddedEventHandler(gvDetail1_RowsAdded);
            gvDetail2.RowsAdded += new DataGridViewRowsAddedEventHandler(gvDetail1_RowsAdded);
            gvDetail3.RowsAdded += new DataGridViewRowsAddedEventHandler(gvDetail1_RowsAdded);
            gvDetail1.RowsRemoved += new DataGridViewRowsRemovedEventHandler(gvDetail1_RowsRemoved);
            gvDetail2.RowsRemoved += new DataGridViewRowsRemovedEventHandler(gvDetail1_RowsRemoved);
            gvDetail3.RowsRemoved += new DataGridViewRowsRemovedEventHandler(gvDetail1_RowsRemoved);
            gvDetail1.CellFormatting += new DataGridViewCellFormattingEventHandler(gvDetail1_CellFormatting);
            gvDetail2.CellFormatting += new DataGridViewCellFormattingEventHandler(gvDetail1_CellFormatting);
            gvDetail3.CellFormatting += new DataGridViewCellFormattingEventHandler(gvDetail1_CellFormatting);

            gvDetail1.AutoGenerateColumns = false;
            gvDetail2.AutoGenerateColumns = false;
            gvDetail3.AutoGenerateColumns = false;

            gvDetail1.DataSource = dataSet1;
            gvDetail1.DataMember = "tDetail1";
            gvDetail2.DataSource = dataSet1;
            gvDetail2.DataMember = "tDetail1.Relation1";
            gvDetail3.DataSource = dataSet1;
            gvDetail3.DataMember = "tDetail1.Relation1.Relation2";

            //dataGridView1.DataSource = tDetail1;
            //dataGridView2.DataSource = tDetail2;
            //dataGridView3.DataSource = tDetail3;
            //dataGridView1.AutoGenerateColumns = true;
            //dataGridView2.AutoGenerateColumns = true;
            //dataGridView3.AutoGenerateColumns = true;

            //生产部门 -> cCombo.Items
            DataGridViewComboBoxColumn cCombo = (DataGridViewComboBoxColumn)gvDetail1.Columns["DepartmentName"];
            TB_Department[] tDeaprtments = BaseDataProxy.FindDepartments(null,null,null);
            IEnumerable<TB_Department> query = tDeaprtments.OrderBy(TB_Department => TB_Department.name);
            foreach (TB_Department dp in query)
            {
                cCombo.Items.Add(dp.name);
            }
        }

        #endregion

        #region 自定义过程/函数

        /// <summary>
        /// 建立 DataTable 与 GridView 中字段的对应关系,在后面的数据互相转换(DataTable - GridView)中使用此处建立的关系
        /// </summary>
        /// <param name="tDetail"></param>
        /// <param name="gvDetail"></param>
        /// <returns></returns>
        private bool CreateFieldRef(DataTable tDetail, DataGridView gvDetail)
        {
            FieldsRef.Clear();
            foreach (DataColumn dc in tDetail.Columns)
            {
                string cName = dc.ColumnName;
                bool bFind = false;
                foreach (DataGridViewColumn dgvc in gvDetail.Columns)
                {
                    if (dgvc.DataPropertyName.ToLower() == cName.ToLower())
                    {
                        FieldsRef.Add(dgvc.Name);
                        bFind = true;
                        break;
                    }
                }
                if (!bFind)
                    FieldsRef.Add("");
            }
            return true;
        }

        /// <summary>
        /// datatable -> gridview， datatable记录填入到gridview
        /// </summary>
        /// <param name="tDetail"></param>
        /// <param name="gvDetail"></param>
        /// <returns></returns>
        private bool DataTableToGridView(DataTable tDetail, DataGridView gvDetail)
        {
            CreateFieldRef(tDetail, gvDetail);
            gvDetail.SuspendLayout();
            gvDetail.Rows.Clear();

            foreach (DataRow dr in tDetail.Rows)
            {
                int rIndex = gvDetail.Rows.Add();

                int iindex = 0;
                foreach (string fName in FieldsRef)
                {
                    if (string.IsNullOrEmpty(fName))
                    {
                        iindex++;
                        continue;
                    }
                    gvDetail.Rows[rIndex].Cells[fName].Value = dr[iindex].ToString();
                    iindex++;
                }
            }
            gvDetail.ResumeLayout();
            return true;
        }

        /// <summary>
        /// gridview -> datatable， gridview记录填入到datatable
        /// </summary>
        /// <param name="gvDetail"></param>
        /// <param name="tDetail"></param>
        /// <returns></returns>
        private bool GridViewToDataTable(DataGridView gvDetail, DataTable tDetail)
        {
            CreateFieldRef(tDetail, gvDetail);
            tDetail.Clear();

            for (int i = 0; i < gvDetail.Rows.Count; i++)
            {
                DataRow NewDetailRow = tDetail.NewRow();
                int iindex = 0;
                foreach (string fName in FieldsRef)
                {
                    if (string.IsNullOrEmpty(fName))
                    {
                        iindex++;
                        continue;
                    }

                    try
                    {
                        NewDetailRow[iindex] = gvDetail.Rows[i].Cells[fName].Value;
                    }
                    catch
                    {
                        // 忽略转换错误，默认值为空
                    }
                    finally
                    {
                        iindex++;
                    }
                }
                tDetail.Rows.Add(NewDetailRow);
            }
            return true;

        }

        /// <summary>
        /// 重写继承窗体中编辑状态转换后的处理代码
        /// </summary> 
        public override void EditStatusChanged()
        {
            RefreshStatus();
            //btnAppend.Enabled = (EditStatus != Common.BillOperateType.Add) && (EditStatus != Common.BillOperateType.Update);
            //btnOrder.Enabled = bEdit;
            //btnOpen.Enabled = (EditStatus == Common.BillOperateType.None);

            btnSave.Enabled = bEdit;
            btnDelete.Enabled = bEdit;

            btnAddPrd.Enabled = bEdit;
            btnDelPrd.Enabled = bEdit;
            btnMaterial.Enabled = bEdit;

            btnAddProc.Enabled = bEdit;
            btnDelProc.Enabled = bEdit;
            btnImpPrj.Enabled = bEdit;

            btnAddItem.Enabled = bEdit;
            btnDelItem.Enabled = bEdit;
            btnConfirm.Enabled = bConfirm;
            btnPrint.Enabled = bPrint;
        }

        private void RefreshStatus()
        {
            bEdit = (EditStatus == Common.BillOperateType.Add) || (EditStatus == Common.BillOperateType.Update);
            bConfirm = (tMain.Rows.Count > 0);
            if (bConfirm)
                bConfirm = (Common.StringToInt(tMain.Rows[0]["id"].ToString()) > 0);
            bPrint = (EditStatus != Common.BillOperateType.Add) && (EditStatus != Common.BillOperateType.Update);
        }

        private void UpdateGroupButton(int iTag)
        {
            bool bEnabled = (EditStatus == Common.BillOperateType.Add) || (EditStatus == Common.BillOperateType.Update);

            btnAddPrd.Enabled = (iTag == 0) && bEnabled;
            btnDelPrd.Enabled = (iTag == 0) && bEnabled;
            btnMaterial.Enabled = (iTag == 0) && bEnabled;
            //btnOrder.Enabled = (iTag == 0) && bEnabled;

            btnAddProc.Enabled = (iTag == 1) && bEnabled;
            btnDelProc.Enabled = (iTag == 1) && bEnabled;
            btnImpPrj.Enabled = (iTag == 1) && bEnabled;

            btnAddItem.Enabled = (iTag == 2) && bEnabled;
            btnDelItem.Enabled = (iTag == 2) && bEnabled;
        }

        /// <summary>
        /// 编辑控件的输入状态控制
        /// </summary> 
        private void DisabledControls()
        {
            SetControlsStatus(false);
        }

        /// <summary>
        /// 编辑控件的输入状态控制
        /// </summary>
        private void EnabledControls()
        {
            SetControlsStatus(true);
        }

        private void SetControlsStatus(bool SetEnabledFlag)
        {
            //edtBillCode.Enabled = SetEnabledFlag;
            edtBillDate.Enabled = SetEnabledFlag;
            //chkWClose.Enabled = SetEnabledFlag;
            //chkMClose.Enabled = SetEnabledFlag;
            edtBillStatus.Enabled = SetEnabledFlag;

            edtDepartment.Enabled = SetEnabledFlag;

            edtMemo.Enabled = SetEnabledFlag;
            //edtCreateTime.Enabled = SetEnabledFlag;

            gvDetail1.ReadOnly = !SetEnabledFlag;
            gvDetail2.ReadOnly = !SetEnabledFlag;
            gvDetail3.ReadOnly = !SetEnabledFlag;

            //指定表格中只读的字段，防止被用户错误修改
            if (SetEnabledFlag)
            {
                gvDetail1.Columns["structLevel"].ReadOnly = SetEnabledFlag;
                gvDetail1.Columns["orderNum"].ReadOnly = SetEnabledFlag;
                gvDetail1.Columns["MaterialName"].ReadOnly = SetEnabledFlag;
                gvDetail1.Columns["workCode"].ReadOnly = SetEnabledFlag;
                gvDetail1.Columns["specs"].ReadOnly = SetEnabledFlag;
                gvDetail1.Columns["Unit"].ReadOnly = SetEnabledFlag;
                gvDetail1.Columns["finishNum"].ReadOnly = SetEnabledFlag;
                gvDetail1.Columns["recvFinish"].ReadOnly = SetEnabledFlag;
                gvDetail1.Columns["prdnFinish"].ReadOnly = SetEnabledFlag;
                gvDetail1.Columns["CategoryName"].ReadOnly = SetEnabledFlag;
                gvDetail1.Columns["PrdtPrjtCode"].ReadOnly = SetEnabledFlag;
                gvDetail1.Columns["TraderName"].ReadOnly = SetEnabledFlag;

                gvDetail2.Columns["sort"].ReadOnly = SetEnabledFlag;
                gvDetail2.Columns["WorkstageName"].ReadOnly = SetEnabledFlag;
                gvDetail2.Columns["ManhourUnit"].ReadOnly = SetEnabledFlag;
                gvDetail2.Columns["fixWastage"].ReadOnly = SetEnabledFlag;
                gvDetail2.Columns["wastageRate"].ReadOnly = SetEnabledFlag;
                gvDetail2.Columns["inNum"].ReadOnly = SetEnabledFlag;
                gvDetail2.Columns["outNum"].ReadOnly = SetEnabledFlag;

                gvDetail3.Columns["sort2"].ReadOnly = SetEnabledFlag;
                gvDetail3.Columns["MaterialName2"].ReadOnly = SetEnabledFlag;
                gvDetail3.Columns["Category"].ReadOnly = SetEnabledFlag;
                gvDetail3.Columns["Specs2"].ReadOnly = SetEnabledFlag;
                gvDetail3.Columns["Expire"].ReadOnly = SetEnabledFlag;
                gvDetail3.Columns["Unit2"].ReadOnly = SetEnabledFlag;
                gvDetail3.Columns["recvMtrlClosed"].ReadOnly = SetEnabledFlag;
                gvDetail3.Columns["cancelFinish"].ReadOnly = SetEnabledFlag;
                gvDetail3.Columns["overCancel"].ReadOnly = SetEnabledFlag;
                gvDetail3.Columns["fixWastage2"].ReadOnly = SetEnabledFlag;
                gvDetail3.Columns["wastageRate2"].ReadOnly = SetEnabledFlag;
            }

            UpdateGroupButton(tabControl1.SelectedIndex);
        }

        /// <summary>
        /// 绑定数据到编辑控件
        /// </summary>
        private void SetControlsData()
        {
            string strDayTime;

            edtBillCode.Text = tMain.Rows[0]["code"].ToString();
            edtBillDate.Text = tMain.Rows[0]["pDate"].ToString();
            if (!string.IsNullOrEmpty(tMain.Rows[0]["warehouseClosed"].ToString()))
                chkWClose.Checked = (bool)tMain.Rows[0]["warehouseClosed"];
            else
                chkWClose.Checked = false;
            if (!string.IsNullOrEmpty(tMain.Rows[0]["recvMtrlClosed"].ToString()))
                chkMClose.Checked = (bool)tMain.Rows[0]["recvMtrlClosed"];
            else
                chkMClose.Checked = false;
            edtBillStatus.Text = tMain.Rows[0]["status"].ToString();

            if (!string.IsNullOrEmpty(tMain.Rows[0]["department"].ToString()))
            {
                SelectItem item = new SelectItem();
                TB_Department Department = BaseDataProxy.GetDepartment((int)tMain.Rows[0]["department"]);
                if (Department != null)
                {
                    item.Name = Department.name;
                    item.Key = Department.code;
                    item.Value = Department.id.ToString();
                    edtDepartment.SetSelected(item);
                }
            }
            edtMemo.Text = tMain.Rows[0]["memo"].ToString();

            edtOperator.Text = tMain.Rows[0]["OperatorName"].ToString();
            edtMender.Text = tMain.Rows[0]["MenderName"].ToString();
            edtAssessor.Text = tMain.Rows[0]["AssessorName"].ToString();

            strDayTime = tMain.Rows[0]["pDate"].ToString();
            if (!String.IsNullOrEmpty(strDayTime))
                edtCreateTime.Value = Convert.ToDateTime(strDayTime);

            strDayTime = tMain.Rows[0]["createTime"].ToString();
            if (!String.IsNullOrEmpty(strDayTime))
                edtCreateTime.Text = strDayTime;

            strDayTime = tMain.Rows[0]["updateTime"].ToString();
            if (!String.IsNullOrEmpty(strDayTime))
                edtUpdateTime.Text = strDayTime;

            strDayTime = tMain.Rows[0]["verifyTime"].ToString();
            if (!String.IsNullOrEmpty(strDayTime))
                edtVerifyTime.Text = strDayTime;


        }

        /// <summary>
        /// 编辑控件绑定数据保存回datatable
        /// </summary>
        /// <returns></returns> 
        private bool GetControlsData()
        {
            if (tMain.Rows[0]["department"] == null) // edtDepartment.SelectedValue();
            {
                MessageBox.Show("保存单据中部门不可为空。");
                return false;
            }

            tMain.Rows[0]["memo"] = edtMemo.Text;

            if ((tDetail1.Rows.Count == 0) || (tDetail2.Rows.Count == 0) || (tDetail2.Rows.Count == 0))
            {
                MessageBox.Show("单据明细记录为空不可以保存。");
                return false;
            }

            //foreach (DataGridViewRow TheRow in gvDetail1.Rows)
            //{
            //    if ((string.IsNullOrEmpty(TheRow.Cells["MaterialId"].Value.ToString())) || (string.IsNullOrEmpty(TheRow.Cells["MaterialCode"].Value.ToString())))
            //    {
            //        gvDetail1.CurrentCell = TheRow.Cells["MaterialCode"];
            //        MessageBox.Show("输入的物资不正确，请重新输入。");
            //        return false;
            //    }
            //}

            //if (EditStatus == Common.BillOperateType.Add)
            //{
            //    tMain.Rows[0]["operator"] = SysLoginUserInfo.UserId;
            //    tMain.Rows[0]["createTime"] = DateTime.Now;
            //    tMain.Rows[0]["status"] = "未批";
            //}
            //if (EditStatus == Common.BillOperateType.Update)
            //{
            //    tMain.Rows[0]["mender"] = SysLoginUserInfo.UserId;
            //    tMain.Rows[0]["updateTime"] = DateTime.Now;
            //}

            //GridViewToDataTable(gvDetail1, tDetail1);
            //GridViewToDataTable(gvDetail2, tDetail2);
            //GridViewToDataTable(gvDetail3, tDetail3);

            return true;
        }


        /// <summary>
        /// 选择已保存单据，打开继续上一次编辑
        /// </summary>
        /// <param name="BillId"></param>
        private void OpenBill(int BillId)
        {
            XProduction xMain = BaseDataProxy.GetXProduction(BillId);
            XPrdnDetail[] xDetials1 = BaseDataProxy.GetXPrdnDetails(BillId);
            List<XPrdnWorkstage> lDetail2 = new List<XPrdnWorkstage>();
            List<XPrdnMaterial> lDetail3 = new List<XPrdnMaterial>();

            if ((xMain == null) || (xDetials1 == null))
                return;

            foreach (XPrdnDetail xDetail1 in xDetials1)
            {
                XPrdnWorkstage[] xDetials2ChildRows = BaseDataProxy.GetXPrdnWorkstages(xDetail1.PrdnDetail.id);
                lDetail2.AddRange(xDetials2ChildRows);
                foreach (XPrdnWorkstage xDetail2 in xDetials2ChildRows)
                {
                    XPrdnMaterial[] xDetials3ChildRows = BaseDataProxy.GetXPrdnMaterials(xDetail2.PrdnWorkstage.id);
                    lDetail3.AddRange(xDetials3ChildRows);
                }
            }

            //表头内容
            IEnumerable<XProduction> ary = new List<XProduction>() { xMain };
            tMain = ary.ConvertToDataTable<TB_Production>();
            //表体内容
            DataTable tmDetail1 = xDetials1.ConvertToDataTable<TB_PrdnDetail>();
            DataTable tmDetail2 = lDetail2.ConvertToDataTable<TB_PrdnWorkstage>();
            DataTable tmDetail3 = lDetail3.ConvertToDataTable<TB_PrdnMaterial>();

            tDetail3.Clear();
            tDetail2.Clear();
            tDetail1.Clear();

            gvDetail1.SuspendLayout();
            CopyTable(tmDetail1, tDetail1);
            //gvDetail1.AutoResizeColumns();
            gvDetail1.ResumeLayout();

            gvDetail2.SuspendLayout();
            CopyTable(tmDetail2, tDetail2);
            //gvDetail2.AutoResizeColumns();
            gvDetail2.ResumeLayout();

            gvDetail3.SuspendLayout();
            CopyTable(tmDetail3, tDetail3);
            //gvDetail3.AutoResizeColumns();
            gvDetail3.ResumeLayout();

            //if (!string.IsNullOrEmpty(tMain.Rows[0]["assessor"].ToString()))
            if ((bool)tMain.Rows[0]["isVerify"] == true)
            {
                //审批后,不允许再修改
                EditStatus = Common.BillOperateType.View;
                SetControlsStatus(false);
            }
            else
            {
                //未审批,允许再修改
                tMain.Rows[0]["mender"] = SysLoginUserInfo.UserId;
                tMain.Rows[0]["MenderName"] = SysLoginUserInfo.UserName;
                tMain.Rows[0]["updateTime"] = DateTime.Now;
                EditStatus = Common.BillOperateType.Update;
                SetControlsStatus(true);
            }

            SetControlsData();
        }

        private void CopyTable(DataTable tFrom, DataTable tTo)
        {
            FieldsRef.Clear();
            foreach (DataColumn dcTo in tTo.Columns)
            {
                string cName = dcTo.ColumnName;
                bool bFind = false;
                foreach (DataColumn dcFrom in tFrom.Columns)
                {
                    if (dcFrom.ColumnName.ToLower() == cName.ToLower())
                    {
                        FieldsRef.Add(dcFrom.ColumnName);
                        bFind = true;
                        break;
                    }
                }
                if (!bFind)
                    FieldsRef.Add("");
            }

            tTo.Clear();

            foreach (DataRow drFrom in tFrom.Rows)
            {
                DataRow NewDetailRow = tTo.NewRow();
                int iindex = 0;
                foreach (string fName in FieldsRef)
                {
                    if (string.IsNullOrEmpty(fName))
                    {
                        iindex++;
                        continue;
                    }

                    try
                    {
                        NewDetailRow[iindex] = drFrom[fName]; //.ToString()
                    }
                    catch
                    {
                        // 忽略转换错误，默认值为空
                    }
                    finally
                    {
                        iindex++;
                    }
                }
                tTo.Rows.Add(NewDetailRow);
            }
        }

        /// <summary>
        /// 从上一业务流程导入单据内容
        /// </summary>
        /// <param name="iBillId"></param>
        /// <param name="MaterialId"></param>
        private void ImportBill(int BillId, int MaterialId)
        {
            if ((BillId == 0) || (MaterialId == 0))
            {
                MessageBox.Show("选定导入的单号或产品号不正确。");
                return;
            }
            if (tMain.Rows.Count == 0)
                btnAppend_Click(null, null);
            gvDetail1NewRow();
            DataRow dr = tDetail1.Rows[tDetail1.Rows.Count - 1];
            XOrder xOrder = BaseDataProxy.GetXOrder(BillId);
            dr["orderId"] = BillId;
            dr["orderCode"] = xOrder.Order.code;
            XOrderDetail[] xOrderDetails = BaseDataProxy.GetXOrderDetails(BillId);
            foreach (XOrderDetail xOrderDetail in xOrderDetails)
            {
                if (xOrderDetail.OrderDetail.material == MaterialId)
                {
                    dr["orderDetailId"] = xOrderDetail.OrderDetail.id;
                    dr["orderNum"] = Common.StringToInt(xOrderDetail.OrderDetail.num.ToString());
                    dr["planOutput"] = Common.StringToInt(xOrderDetail.OrderDetail.num.ToString());
                    dr["material"] = xOrderDetail.OrderDetail.material;
                    dr["materialCode"] = xOrderDetail.OrderDetail.materialCode;
                    dr["MaterialName"] = xOrderDetail.MaterialName;
                    dr["specs"] = xOrderDetail.OrderDetail.specs;
                    dr["PrdtPrjtCode"] = xOrderDetail.PrdtPrjtCode;
                    dr["Unit"] = xOrderDetail.Unit;
                    XOrder xO = BaseDataProxy.GetXOrder(xOrderDetail.OrderDetail.orderId);
                    if (xO != null)
                        dr["TraderName"] = xO.TraderName;
                    TB_Material tMaterial = BaseDataProxy.GetMaterial((int)xOrderDetail.OrderDetail.material);
                    TB_Options tOption = BaseDataProxy.GetOption((int)tMaterial.category);
                    dr["CategoryName"] = tOption.name;
                    break;
                }
            }
        }

        private void FindProduct()
        {
            FindMaterialFrm frm = new FindMaterialFrm();
            frm.Text = "选择产品";
            if (frm.ShowDialog() == DialogResult.OK)
            {
                gvDetail1.CurrentRow.Cells["MaterialId"].Value = frm.SelectorItem.Id;
                gvDetail1.CurrentRow.Cells["MaterialCode"].Value = frm.SelectorItem.Code;
                gvDetail1.CurrentRow.Cells["MaterialName"].Value = frm.SelectorItem.CnName;
                gvDetail1.CurrentRow.Cells["Specs"].Value = frm.SelectorItem.Specs;
                gvDetail1.CurrentRow.Cells["Unit"].Value = frm.SelectorItem.Unit;
                TB_Material tMaterial = BaseDataProxy.GetMaterial(frm.SelectorItem.Id);
                gvDetail1.CurrentRow.Cells["PrdtPrjtCode"].Value = tMaterial.projectCode;
                TB_Options tOption = BaseDataProxy.GetOption((int)tMaterial.category);
                gvDetail1.CurrentRow.Cells["CategoryName"].Value = tOption.name;
            }
        }

        private void ImportProject(int prjtId)
        {
            int pLevel = 0;
            decimal pOrderNum = 0;
            TB_ProductProject pp = this.BaseDataProxy.GetPrdtPrjt(prjtId);
            if (pp != null)
            {
                pLevel++;//层数累计
                XPrjtWorkstage[] pws = this.BaseDataProxy.FindPrjtWorkstages(pp.id);
                if (pws != null)
                {
                    foreach (XPrjtWorkstage pw in pws)
                    {
                        XPrjtElement[] pes = this.BaseDataProxy.FindPrjtElements(pw.PrjtWorkstage.id);
                        foreach (XPrjtElement pe in pes)
                        {
                            XMaterial material = this.BaseDataProxy.GetXMaterial(Convert.ToInt32(pe.PrjtElement.material), null,null);
                            if (material != null)
                            {
                                decimal num = 0;
                                
                                    num = pOrderNum * pe.PrjtElement.dosage;

                                decimal? currentStock = this.BaseDataProxy.GetCurrentStock(material.Material.id);

                                //this.dataGridView1.Rows.Add(new object[] { null, pLevel,orderId, orderCode,null, material.Material.id, material.Material.code, material.Material.cnName,
                                //    material.Material.specs, pe.NextPrjtId,pe.NextPrjtCode, null,num,num,DateTime.Now.ToShortDateString(),DateTime.Now.ToShortDateString(),
                                //    material.Material.source,material.Material.department,material.DepartmentName,currentStock,currentStock,currentStock,num,num,material.CategoryName,material.Material.unit,
                                //    material.Material.isNominal,this.txtBoxCode.Text,this._Id});
                                //if (pe.NextPrjtId != null)
                                //    addPrjtMaterials(pLevel, Convert.ToInt32(pe.NextPrjtId), num, orderId, orderCode);
                            }
                        }
                    }
                }
            }
        }

        private void ImportPrjtWorkstage(int ProjectId)
        {

        }

        private void ImportPrjtElement(int ProjectId, decimal pOrderNum)
        {
            int pLevel = 0;
            //decimal pOrderNum = 0;
            //工程
            TB_ProductProject pp = this.BaseDataProxy.GetPrdtPrjt(ProjectId);
            if (pp != null)
            {
                pLevel++;//层数累计
                //工序
                XPrjtWorkstage[] pws = this.BaseDataProxy.FindPrjtWorkstages(pp.id);
                if (pws != null)
                {
                    foreach (XPrjtWorkstage pw in pws)
                    {
                        //物料
                        XPrjtElement[] pes = this.BaseDataProxy.FindPrjtElements(pw.PrjtWorkstage.id);
                        foreach (XPrjtElement pe in pes)
                        {
                            XMaterial material = this.BaseDataProxy.GetXMaterial(Convert.ToInt32(pe.PrjtElement.material), null,null);
                            if (material != null)
                            {
                                decimal num = 0;
                                    num = pOrderNum * pe.PrjtElement.dosage;

                                decimal? currentStock = this.BaseDataProxy.GetCurrentStock(material.Material.id);

                                //新行默认值设定
                                gvDetail3NewRow();
                                //将工程包含物料详细资料写入新行
                                DataRow dr = tDetail3.Rows[tDetail3.Rows.Count - 1];
                                dr["Category"] = material.CategoryName;
                                //dr["Expire"] = material.DepotName;
                                dr["MaterialCode"] = material.Material.code;
                                dr["MaterialName"] = material.Material.cnName;
                                dr["Specs"] = material.Material.specs;
                                dr["Unit"] = material.Material.unit;
                                //dr["id"] = 1;
                                //dr["prdnWorkstageId"] = 1;
                                dr["material"] = material.Material.id;
                                //dr["sort"] = 1;
                                dr["dosage"] = num; // pe.PrjtElement.dosage;
                                //dr["issueNum"] = pe.PrjtElement.;
                                dr["fixWastage"] = pe.PrjtElement.fixWastage;
                                dr["wastageRate"] = pe.PrjtElement.wastageRate;
                                //dr["recvMtrlClosed"] = 1;
                                //dr["overCancel"] = 1;
                                //dr["cancelFinish"] = 1;

                                if (pe.NextPrjtId != null)
                                    ImportPrjtElement(Convert.ToInt32(pe.NextPrjtId), num);
                            }
                        }
                    }
                }
            }

        }

        #endregion

        #region 按钮部分
        private void btnAppend_Click(object sender, EventArgs e)
        {
            ////放弃新单
            //if (EditStatus == Common.BillOperateType.Add)
            //{
            //    EditStatus = Common.BillOperateType.None;
            //    SetControlsStatus(false);
            //    return;
            //}

            //新单输入
            EditStatus = Common.BillOperateType.Add;
            SetControlsStatus(true);

            tMain.Clear();
            DataRow NewMainRow = tMain.NewRow();

            NewMainRow["code"] = ""; // BaseDataProxy.GetSerialNo(1, BillPrefix, 4, true, true, true);
            NewMainRow["operator"] = SysLoginUserInfo.UserId;
            NewMainRow["OperatorName"] = SysLoginUserInfo.UserName;
            NewMainRow["createTime"] = DateTime.Now;
            NewMainRow["pDate"] = DateTime.Now;
            NewMainRow["warehouseClosed"] = 0;
            NewMainRow["recvMtrlClosed"] = 0;
            NewMainRow["id"] = 1;
            NewMainRow["isVerify"] = false;
            NewMainRow["isClosed"] = false;
            NewMainRow["status"] = "未批";
            tMain.Rows.Add(NewMainRow);

            tDetail3.Clear();
            tDetail2.Clear();
            tDetail1.Clear();

            SetControlsData();

            //gvDetail1NewRow();
            //gvDetail2NewRow();
            //gvDetail3NewRow();

        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            SelectBillFrm frm = new SelectBillFrm();
            frm.SetCondition(GRWL.BZSC.Common.EnumCommon.BillType.SCD, BillPrefix, false);
            frm.ShowDialog();
            if (frm.SelectBills.Count > 0)
            {
                OpenBill(frm.SelectBills[0].BillId);
            }

        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if ((EditStatus != Common.BillOperateType.Add) & (EditStatus != Common.BillOperateType.Update) & (EditStatus != Common.BillOperateType.Delete))
                return;

            //保存修改
            if (!GetControlsData())
                return;

            if ((EditStatus == Common.BillOperateType.Add) && string.IsNullOrEmpty(tMain.Rows[0]["code"].ToString()))
            {
                tMain.Rows[0]["code"] = BaseDataProxy.GetSerialNo(1, BillPrefix, 4, true, true, true);
                edtBillCode.Text = tMain.Rows[0]["code"].ToString();
            }
            tMain.AcceptChanges();

            foreach (DataRow dr in tDetail1.Rows)
            {
                if (string.IsNullOrEmpty(dr["prdnCode"].ToString()))
                    dr["prdnCode"] = tMain.Rows[0]["code"];
            }
            tDetail1.AcceptChanges();

            tDetail2.AcceptChanges();
            tDetail3.AcceptChanges();

            //将 DataTable 转换为写入后台格式 TB_xxxxx
            TB_Production tbMain = OTConverter.ConvertToObject<TB_Production>(tMain.Rows[0]);

            //修改datatable后，刷新写入内容
            List<TB_PrdnDetail> lsDetails1 = OTConverter.ConvertTableToObject<TB_PrdnDetail>(tDetail1);
            TB_PrdnDetail[] tbDetails1 = lsDetails1.ToArray();

            List<TB_PrdnWorkstage> lsDetails2 = null;
            TB_PrdnWorkstage[] tbDetails2 = null;

            List<TB_PrdnMaterial> lsDetails3 = null;
            TB_PrdnMaterial[] tbDetails3 = null;

            int iIndexLv1 = 0;
            DataTable dChilds2 = null;
            DataTable dChilds3 = null;
            foreach (DataRow drLv1 in tDetail1.Rows)
            {
                DataRow[] drsLv2 = drLv1.GetChildRows("Relation1");
                tbDetails2 = null;

                if (drsLv2.Count() > 0)
                {
                    dChilds2 = drsLv2.CopyToDataTable();
                    lsDetails2 = OTConverter.ConvertTableToObject<TB_PrdnWorkstage>(dChilds2);
                    tbDetails2 = lsDetails2.ToArray();
                    int iIndexLv2 = 0;

                    foreach (DataRow drLv2 in dChilds2.Rows)
                    {
                        DataRow dr = tDetail2.Rows.Find(drLv2["id"].ToString());
                        DataRow[] drsLv3 = dr.GetChildRows("Relation2");
                        tbDetails3 = null;

                        if (drsLv3.Count() > 0)
                        {
                            dChilds3 = drsLv3.CopyToDataTable();
                            lsDetails3 = OTConverter.ConvertTableToObject<TB_PrdnMaterial>(dChilds3);
                            tbDetails3 = lsDetails3.ToArray();
                        }
                        tbDetails2[iIndexLv2].TB_PrdnMaterial = tbDetails3;
                        iIndexLv2++;
                    }
                }

                tbDetails1[iIndexLv1].TB_PrdnWorkstage = tbDetails2;
                iIndexLv1++;
            }
            tbMain.TB_PrdnDetail = tbDetails1;

            int iAddID = -1;
            bool bUpdate = false;

            if (EditStatus == Common.BillOperateType.Add)
            {
                //保存方法，支持主/细单一次写入到后台。
                iAddID = BaseDataProxy.AddProduction(tbMain);
                tMain.Rows[0]["id"] = iAddID;
            }
            else // (EditStatus == Common.BillOperateType.Update)
            {
                bUpdate = BaseDataProxy.UpdateProduction(tbMain);
            }

            if (((EditStatus == Common.BillOperateType.Add) && (iAddID > 0)) || ((EditStatus == Common.BillOperateType.Update) && (bUpdate)))
            {
                MessageBox.Show("已成功保存单据.");
                EditStatus = Common.BillOperateType.Update;
                OpenBill((int)tMain.Rows[0]["id"]);
                //SetControlsStatus(false);
            }
            else
                MessageBox.Show("保存单据失败.");

        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            //if (!string.IsNullOrEmpty(tMain.Rows[0]["assessor"].ToString()))
            if ((bool)tMain.Rows[0]["isVerify"] == true)
            {
                MessageBox.Show("无法删除已审批单据.");
                return;
            }

            if ((EditStatus != Common.BillOperateType.Add) & (EditStatus != Common.BillOperateType.Update))
                return;

            if (EditStatus == Common.BillOperateType.Add)
            {
                int BillId = Common.StringToInt(tMain.Rows[0]["id"].ToString());
                string message = "是否删除单据？";
                string caption = "确认";
                MessageBoxButtons buttons = MessageBoxButtons.YesNo;
                DialogResult result = MessageBox.Show(message, caption, buttons);
                if (result != DialogResult.Yes)
                    return;

                tDetail3.Rows.Clear();
                tDetail2.Rows.Clear();
                tDetail1.Rows.Clear();
                tMain.Rows.Clear();
                return;
            }

            if (EditStatus == Common.BillOperateType.Update)
            {
                if (tMain.Rows[0]["id"] == null)
                    return;

                int BillId = Common.StringToInt(tMain.Rows[0]["id"].ToString());
                string message = "是否删除单据？";
                string caption = "确认";
                MessageBoxButtons buttons = MessageBoxButtons.YesNo;
                DialogResult result = MessageBox.Show(message, caption, buttons);
                if (result != DialogResult.Yes)
                    return;

                bool bDelOk = BaseDataProxy.DeleteProduction(BillId);
                if (bDelOk)
                {
                    MessageBox.Show("已成功删除单据.");
                    EditStatus = Common.BillOperateType.View;
                }
                else
                {
                    MessageBox.Show("无法删除单据.");
                    return;
                }

            }

            // 初始化所有记录
            tMain.Rows.Clear();
            tDetail1.Rows.Clear();
            tDetail2.Rows.Clear();
            tDetail3.Rows.Clear();
            tMain.Rows.Add();

            SetControlsData();
            SetControlsStatus(false);

            EditStatus = Common.BillOperateType.None;
            return;

        }

        private void btnAddPrd_Click(object sender, EventArgs e)
        {
            gvDetail1NewRow();
        }

        private void btnDelPrd_Click(object sender, EventArgs e)
        {
            if (gvDetail1.RowCount > 0)
            {
                gvDetail1.Rows.RemoveAt(gvDetail1.CurrentRow.Index);
                tDetail1.AcceptChanges();
                // 删除所有记录后，自动建立一个空白记录
                if (gvDetail1.RowCount == 0)
                {
                    gvDetail1NewRow();
                    tDetail1.AcceptChanges();
                }
            }
        }

        private void btnMaterial_Click(object sender, EventArgs e)
        {
            FindProduct();
        }

        private void btnOrder_Click(object sender, EventArgs e)
        {
            SelectBillFrm frm = new SelectBillFrm();
            frm.SetCondition(GRWL.BZSC.Common.EnumCommon.BillType.DH, "DH", true);
            frm.ShowDialog();
            foreach (GRWL.BZSC.UI.SelectBillFrm.SelectBillsInfo SBI in frm.SelectBills)
            {
                ImportBill(SBI.BillId, SBI.MateriailId);
            }
        }

        private void btnAddProc_Click(object sender, EventArgs e)
        {
            gvDetail2NewRow();

        }

        private void btnDelProc_Click(object sender, EventArgs e)
        {
            if (gvDetail2.RowCount > 0)
            {
                gvDetail2.Rows.RemoveAt(gvDetail2.CurrentRow.Index);
                tDetail2.AcceptChanges();
                // 删除所有记录后，自动建立一个空白记录
                if (gvDetail2.RowCount == 0)
                {
                    gvDetail2NewRow();
                    tDetail2.AcceptChanges();
                }
            }
        }

        private void btnImpPrj_Click(object sender, EventArgs e)
        {
            FindPrdtPrjtFrm frm = new FindPrdtPrjtFrm(gvDetail1.CurrentRow.Cells["MaterialCode"].Value.ToString());
            frm.ShowDialog();
            if (frm.SelectorItem == null)
                return;

            //导入前清除旧物料
            try
            {
                Cursor = Cursors.WaitCursor;
                int iWorkstageId = Common.StringToInt(gvDetail2.CurrentRow.Cells["id2"].Value.ToString());
                for (int iRec = (tDetail3.Rows.Count - 1); iRec >= 0; iRec--)
                {
                    if (Common.StringToInt(tDetail3.Rows[iRec]["prdnWorkstageId"].ToString()) == iWorkstageId)
                    {
                        tDetail3.Rows.RemoveAt(iRec);
                    }
                }
                gvDetail1.CurrentRow.Cells["PrdtPrjtCode"].Value = frm.SelectorItem.Code;
                ImportPrjtElement(frm.SelectorItem.Id, Common.StringToDecimal(gvDetail1.CurrentRow.Cells["planOutput"].Value.ToString()));
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }

        private void btnAddItem_Click(object sender, EventArgs e)
        {
            gvDetail3NewRow();

        }

        private void btnDelItem_Click(object sender, EventArgs e)
        {
            if (gvDetail3.RowCount > 0)
            {
                gvDetail3.Rows.RemoveAt(gvDetail3.CurrentRow.Index);
                tDetail3.AcceptChanges();
                // 删除所有记录后，自动建立一个空白记录
                if (gvDetail3.RowCount == 0)
                {
                    gvDetail3NewRow();
                    tDetail3.AcceptChanges();
                }
            }
        }

        private void btnConfirm_Click(object sender, EventArgs e)
        {

        }

        private void btnPrint_Click(object sender, EventArgs e)
        {

        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            Close();
        }

        #endregion

        #region 产品部分
        void gvDetail1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            Common.CellFormatColor(sender, e, EditStatus);
        }

        void gvDetail1_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
        {
            Common.ShowDataGridViewRowNo((UDataGridView)sender);
        }

        void gvDetail1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            Common.ShowDataGridViewRowNo((UDataGridView)sender);
        }

        private void gvDetail1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            //MaterialCode
            if (e.ColumnIndex < 0)
                return;

            if ((gvDetail1.Columns[e.ColumnIndex].Name == "MaterialCode") | (gvDetail1.Columns[e.ColumnIndex].Name == "MaterialName"))
            {
                FindProduct();
            }
        }

        private void gvDetail2_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            //WorkstageCode
            if (e.ColumnIndex < 0)
                return;

            if ((gvDetail2.Columns[e.ColumnIndex].Name == "WorkstageCode") | (gvDetail2.Columns[e.ColumnIndex].Name == "WorkstageName"))
            {
                OptionFrm frm = new OptionFrm();
                frm.IsWorkstage = true;
                frm.Text = "选择工序";
                if (frm.ShowDialog() == DialogResult.OK)
                {
                    TB_Workstage xWorkstage = BaseDataProxy.GetWorkstage(Common.StringToInt(frm.SelectorItem.Value));

                    gvDetail2.CurrentRow.Cells["workstage"].Value = xWorkstage.id; // frm.SelectorItem.Key;
                    gvDetail2.CurrentRow.Cells["WorkstageCode"].Value = xWorkstage.code; //frm.SelectorItem.Value;
                    gvDetail2.CurrentRow.Cells["WorkstageName"].Value = xWorkstage.name; //frm.SelectorItem.Name;

                }
            }
        }

        private void gvDetail3_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex < 0)
                return;

            if ((gvDetail3.Columns[e.ColumnIndex].Name == "MaterialCode2") | (gvDetail3.Columns[e.ColumnIndex].Name == "MaterialName2"))
            {
                FindMaterialFrm frm = new FindMaterialFrm();
                frm.Text = "选择物料";
                if (frm.ShowDialog() == DialogResult.OK)
                {
                    gvDetail3.CurrentRow.Cells["MaterialId2"].Value = frm.SelectorItem.Id;
                    gvDetail3.CurrentRow.Cells["MaterialCode2"].Value = frm.SelectorItem.Code;
                    gvDetail3.CurrentRow.Cells["MaterialName2"].Value = frm.SelectorItem.CnName;
                    gvDetail3.CurrentRow.Cells["Specs2"].Value = frm.SelectorItem.Specs;
                    gvDetail3.CurrentRow.Cells["Unit2"].Value = frm.SelectorItem.Unit;
                }
            }
        }

        void gvDetail1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
        }

        private void theView_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            UDataGridView theView = (UDataGridView)sender;
            // 判断所在是否日期选择的列
            if (theView.Columns[e.ColumnIndex].ValueType == typeof(DateTime))
            {
                Rectangle _Rectangle = theView.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true); //得到所在单元格位置和大小
                this._DTP.Size = new Size(_Rectangle.Width, _Rectangle.Height); //把单元格大小赋给时间控件
                this._DTP.Location = new Point(_Rectangle.X, _Rectangle.Y); //把单元格位置赋给时间控件
                if (theView.CurrentCell.Style.BackColor != Color.Empty)
                    _DTP.CalendarForeColor = theView.CurrentCell.Style.BackColor;
                if ((!theView.CurrentCell.ReadOnly) && (!string.IsNullOrEmpty(theView.CurrentCell.Value.ToString())))
                    this._DTP.Value = (DateTime)theView.CurrentCell.Value;
                this._DTP.Visible = true;  //可以显示控件了
            }
            else
            {
                this._DTP.Visible = false;
            }
        }

        private void theView_ColumnWidthChanged(object sender, DataGridViewColumnEventArgs e)
        {
            this._DTP.Visible = false;
        }

        private void theView_Scroll(object sender, ScrollEventArgs e)
        {
            this._DTP.Visible = false;
        }

        private void dtp_TextChange(object sender, EventArgs e)
        {
            theView.CurrentCell.Value = this._DTP.Text.ToString();  //时间控件选择时间时，就把时间赋给所在的单元格
        }

        private int getMaxId(DataTable TheTable)
        {
            int iCount = 0;
            if (TheTable.Rows.Count > 0)
            {
                int iIdx = TheTable.Rows.Count - 1;
                iCount = Common.StringToInt(TheTable.Rows[iIdx]["id"].ToString());
            }
            return iCount;
        }

        private bool gvDetail1NewRow()
        {
            //新行默认值设定
            DataRow dr = tDetail1.NewRow();
            //分配临时id作为关键字引用，写入后台后自动分配为有效值
            dr["id"] = getMaxId(tDetail1) + 1;
            dr["prdn"] = tMain.Rows[0]["id"];
            dr["prdnCode"] = tMain.Rows[0]["code"];
            dr["structLevel"] = 1;
            dr["releaseDate"] = DateTime.Today;
            dr["finishDate"] = DateTime.Today;
            dr["prdnType"] = "自制";
            tDetail1.Rows.Add(dr);
            return true;
        }

        private bool gvDetail2NewRow()
        {
            if (gvDetail1.CurrentRow == null)
                return false;
            //新行默认值设定
            DataRow dr = tDetail2.NewRow();
            //分配临时id作为关键字引用，写入后台后自动分配为有效值
            dr["id"] = getMaxId(tDetail2) + 1;
            dr["sort"] = gvDetail2.Rows.Count + 1; //tDetail2.Rows.Count + 1;
            dr["prdnDetailId"] = gvDetail1.CurrentRow.Cells["id"].Value;
            dr["inNum"] = gvDetail1.CurrentRow.Cells["planOutput"].Value;
            dr["outNum"] = gvDetail1.CurrentRow.Cells["planOutput"].Value;
            dr["ManhourUnit"] = "小时";
            tDetail2.Rows.Add(dr);
            return true;
        }

        private bool gvDetail3NewRow()
        {
            if (gvDetail2.CurrentRow == null)
                return false;
            //新行默认值设定
            DataRow dr = tDetail3.NewRow();
            //分配临时id作为关键字引用，写入后台后自动分配为有效值
            dr["id"] = getMaxId(tDetail3) + 1;
            dr["prdnWorkstageId"] = gvDetail2.CurrentRow.Cells["id2"].Value;
            dr["sort"] = gvDetail1.CurrentRow.Index + 1; //tDetail3.Rows.Count + 1;
            tDetail3.Rows.Add(dr);
            return true;
        }
        #endregion

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            UpdateGroupButton(tabControl1.SelectedIndex);
        }

        private void edtDepartment_SelectorClick(object sender, EventArgs e)
        {
            if ((EditStatus != Common.BillOperateType.Add) & (EditStatus != Common.BillOperateType.Update))
            {
                return;
            }

            DeptFrm frm = new DeptFrm();
            if (frm.ShowDialog() == DialogResult.OK)
            {
                edtDepartment.SetSelected(frm.SelectorItem);
                tMain.Rows[0]["department"] = Common.StringToInt(frm.SelectorItem.Key);
            }

        }

        private void gvDetail1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void btnConfirm_ButtonClick(object sender, EventArgs e)
        {
            btnConfirm.ShowDropDown();
        }

        private void UpdateStatus(int BillId)
        {
            XProduction xMain = BaseDataProxy.GetXProduction(BillId);
            if (xMain.Production.assessor == null)
                tMain.Rows[0]["assessor"] = DBNull.Value;
            else
                tMain.Rows[0]["assessor"] = xMain.Production.assessor;
            if (xMain.Production.verifyTime == null)
                tMain.Rows[0]["verifyTime"] = DBNull.Value;
            else
                tMain.Rows[0]["verifyTime"] = xMain.Production.verifyTime;
            tMain.Rows[0]["status"] = xMain.Production.status;
            tMain.Rows[0]["AssessorName"] = xMain.AssessorName;
            tMain.AcceptChanges();

            edtAssessor.Text = xMain.AssessorName;
            edtVerifyTime.Text = xMain.Production.verifyTime.ToString();
            edtBillStatus.Text = xMain.Production.status;

        }

        private void btnConfirmOK_Click(object sender, EventArgs e)
        {
            try
            {
                int BillId = Common.StringToInt(tMain.Rows[0]["id"].ToString());
                VerifyBillResult vbResult = BaseDataProxy.VerifyBill(BillPrefix, BillId, SysLoginUserInfo.UserId, true);
                MessageBox.Show(vbResult.Message);
                if (vbResult.Pass)
                {
                    //UpdateStatus(BillId);
                    //EditStatus = Common.BillOperateType.View;
                    //SetControlsStatus(false);
                    //gvDetail1.Refresh();
                    //gvDetail2.Refresh();
                    //gvDetail3.Refresh();
                    OpenBill((int)tMain.Rows[0]["id"]);
                }
            }
            catch
            {
            }
        }

        private void btnConfirmCancel_Click(object sender, EventArgs e)
        {
            try
            {
                int BillId = Common.StringToInt(tMain.Rows[0]["id"].ToString());
                VerifyBillResult vbResult = BaseDataProxy.VerifyBill(BillPrefix, BillId, SysLoginUserInfo.UserId, false);
                MessageBox.Show(vbResult.Message);
                if (vbResult.Pass)
                {
                    //UpdateStatus(BillId);
                    //EditStatus = Common.BillOperateType.Update;
                    //SetControlsStatus(true);
                    //gvDetail1.Refresh();
                    //gvDetail2.Refresh();
                    //gvDetail3.Refresh();
                    OpenBill((int)tMain.Rows[0]["id"]);
                }
            }
            catch
            {
            }

        }


        #region 工序部分
        #endregion

        #region 材料部分
        #endregion
    }
}
